//
//  NewsDetailViewController.m
//  MilitaryDemo
//
//  Created by qianfeng01 on 15-7-9.
//  Copyright (c) 2015年 qianfeng01. All rights reserved.
//

#import "NewsDetailViewController.h"
#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "GDataXMLElement+util.h"
#import "DetailModel.h"
#import "HeaderView.h"
#import "DBManager.h"
#import <WebKit/WebKit.h>
#import "aboutModel.h"
@interface NewsDetailViewController ()<UIWebViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)HeaderView *headerView;

@property(nonatomic,strong)DetailModel *detailModel;
@property(nonatomic,strong)UIWebView *webView;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic,strong)UILabel *aboutLable;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArr;
@end

@implementation NewsDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.dataArr=[[NSMutableArray alloc]init];
    [self download];
     [self initUI];

    
}
-(void)initUI
{
    self.headerView=[[[NSBundle mainBundle]loadNibNamed:@"HeaderView" owner:nil options:nil] lastObject];
        [self.headerView.favoriteButton addTarget:self action:@selector(storeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        BOOL isExist=[[DBManager sharedManager]isExistAppForAppId:self.id];
        if (isExist) {
            self.headerView.favoriteButton.enabled=NO;
        }else{
            self.headerView.favoriteButton.enabled=YES;
        }
        [self.headerView.favoriteButton setTitle:@"已收藏" forState:UIControlStateDisabled];
        [self.headerView.favoriteButton setTitle:@"收藏" forState:UIControlStateNormal];
    self.scrollView=[[UIScrollView alloc] initWithFrame:CGRectMake(0,0, kScreenSize.width, kScreenSize.height-64)];
   self.scrollView.showsHorizontalScrollIndicator=NO;
    [self.view addSubview:self.scrollView];
    self.headerView.frame=CGRectMake(0, 0, kScreenSize.width, 115);
    [self.scrollView addSubview:self.headerView];
    CGFloat H=CGRectGetMaxY(self.headerView.frame);
    self.webView=[[UIWebView alloc] initWithFrame:CGRectMake(0,H, self.scrollView.frame.size.width,_scrollView.frame.size.height)];
    self.webView.scrollView.showsHorizontalScrollIndicator=NO;
    self.webView.scrollView.showsVerticalScrollIndicator=NO;
    self.webView.userInteractionEnabled=NO;
    self.webView.delegate=self;
    [self.scrollView addSubview:_webView];

    self.aboutLable=[[UILabel alloc] init];
    self.aboutLable.text=@"热门推荐";
    self.aboutLable.backgroundColor=[UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:0.5];
    [self.scrollView addSubview:_aboutLable];
    
    self.tableView=[[UITableView alloc] init];
    self.tableView.delegate=self;
    self.tableView.dataSource=self;
    [self.scrollView addSubview:self.tableView];
}
-(void)storeButtonClick:(UIButton *)button
{
    button.enabled = NO;
    //收藏 记录到本地数据库
    [[DBManager sharedManager] insertModel:self.detailModel];

}

-(void) download
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    NSString *url=[NSString stringWithFormat:kNewsDetailUrl,self.id];
        __weak typeof (self) weakSelf=self;
        [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
           if (responseObject) {
                NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
                weakSelf.detailModel=[[DetailModel alloc]init];
               [weakSelf.detailModel setValuesForKeysWithDictionary:dict];
               NSString *str=[NSString stringWithFormat:@"<head><style>img{width:300px; height: 250px!important;}</style></head>%@",self.detailModel.webContent];
             [_webView loadHTMLString:str baseURL:nil];


               NSArray *arr=dict[@"aboutNews"];
               for (NSDictionary *aboutDict in arr) {
                   aboutModel *model=[[aboutModel alloc]init];
                   [model setValuesForKeysWithDictionary:aboutDict];
                   [self.dataArr addObject:model];
               }
           }
            [weakSelf.tableView reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"下载推荐数据出错");
        }];

}
-(void)webViewDidStartLoad:(UIWebView *)webView
{
    self.headerView.titleLabel.text=self.detailModel.title;
     self.headerView.authorLabel.text=[NSString stringWithFormat:@"作者:%@",self.detailModel.authorNickName];
}
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
    CGSize Size= [webView sizeThatFits:CGSizeZero];
    CGRect newFrame=webView.frame;
    newFrame.size.height=Size.height;
    _webView.frame=newFrame;
    _scrollView.contentSize=CGSizeMake(kScreenSize.width, self.headerView.frame.size.height+webView.frame.size.height+250+40);
    _aboutLable.frame= CGRectMake(15, 115+Size.height, 100, 20);
    CGFloat h = CGRectGetMaxY(_aboutLable.frame);
    _tableView.frame=CGRectMake(0, h, kScreenSize.width, 250);
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NewsDetailViewController *detail=[[NewsDetailViewController alloc] init];
    aboutModel *model=self.dataArr[indexPath.row];
    detail.id=model.id;
    [self.navigationController pushViewController:detail animated:YES];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellID=@"cellID";
    
    aboutModel *model=self.dataArr[indexPath.row];
    UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell==nil) {
        cell=[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellID];
    }
    cell.textLabel.text=model.title;
    cell.textLabel.font=[UIFont systemFontOfSize:14.0f];
    return cell;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
